package ucadminlogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/key/userkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"time"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type BanUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBanUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BanUserLogic {
	return &BanUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 封号
func (l *BanUserLogic) BanUser(in *pb.BanUserReq) (*pb.BanUserResp, error) {
	defer utils.RecoverPanic()

	var err error
	var ua *usercenter.UserAccount
	ua, err = l.svcCtx.UserAccountModel.FindOne(l.ctx, in.Uid)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	if ua == nil {
		l.Logger.Errorf("user not exist")
		return nil, xerr.NewGrpcErrCodeMsg(xerr.UserNotExist, "用户不存在")
	}

	var ub *usercenter.UserBan
	ub, err = l.svcCtx.UserBanModel.FindOne(l.ctx, in.Uid)
	if err != nil && err != usercenter.ErrNotFound {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	err = l.svcCtx.UserAccountModel.Trans(l.ctx, func(ctx context.Context, tx sqlx.Session) error {
		// 更新封禁信息
		if ub == nil {
			ub = &usercenter.UserBan{
				Uid:           in.Uid,
				BanHours:      in.BanHours,
				BanAdminUid:   in.AdminUid,
				AutoUnbanTime: time.Now().Add(time.Duration(in.BanHours) * time.Hour),
				BanReason:     in.BanReason,
			}
			_, err2 := l.svcCtx.UserBanModel.InsertTrans(ctx, tx, ub)
			if err2 != nil {
				l.Logger.Errorf("err == ", zap.Error(err2))
				return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
			}
		} else {
			ub.AutoUnbanTime = time.Now().Add(time.Duration(in.BanHours) * time.Hour)
			ub.BanReason = in.BanReason
			err2 := l.svcCtx.UserBanModel.UpdateBanState(ctx, tx, ub.Uid, in.AdminUid, ub.BanReason, in.BanHours, &ub.AutoUnbanTime)
			if err2 != nil {
				l.Logger.Errorf("err == ", zap.Error(err2))
				return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
			}
		}
		// 更新账户状态
		err2 := l.svcCtx.UserAccountModel.UpdateAccountState(ctx, tx, in.Uid, ua.AuthKey, ua.AuthType, userkey.AccountStateBan)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		return nil
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	return &pb.BanUserResp{}, nil
}
